<?php

class ConfController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'holidays', 'createHoliday','deleteHoliday','getHolidaysByDate'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Conf;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Conf'])) {
            $model->attributes = $_POST['Conf'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Conf'])) {
            $model->attributes = $_POST['Conf'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Conf');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Conf('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Conf']))
            $model->attributes = $_GET['Conf'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }
    
    public function actionDeleteHoliday(){
        if(isset($_REQUEST['id'])){
            try{
                ResourceTiming::model()->findByPk($_REQUEST['id'])->delete();
                 echo 'Deleted Successfully';
            } catch (Exception $ex) {
                echo 'unable to Delete : '.$ex->getMessage();
            }
        }else{
            echo 'Unable to do this operation ';
            return;
        }
    }

    public function actionHolidays() {
        $holidays_string = "";
        if (!isset($_REQUEST['date'])) {
            $date = date("Y-m-d");
        } else {
            $date = strtotime($_REQUEST['date']);
        }
        $holidays=  ResourceTiming::getAllHolidays($date);
        if (isset($holidays)&&  sizeof($holidays)>0) {
            $holidays_string.= '<table class="cmn_table"><tr><th>Date</th><th>Note</th><th>All day</th><th>Start</th><th>End</th><th>Holiday For</th><th></th></tr>';
            
            foreach ($holidays as $key => $holiday) {
                $_isAllDay='No';
                if(isset($holiday['allDay'])&&$holiday['allDay']==TRUE){
                    $_isAllDay='Yes';
                }
                $_leaveFor='Organization';
                if(isset($holiday['resource'])){
                    $_leaveFor=  User::model()->findByPk($holiday['resource'])->profile->name;
                }
                
                $holidays_string.='<tr><td>' . $holiday['eventOn'] . '</td><td>' . $holiday['note'] . '</td><td>' .
                $_isAllDay . '</td><td>' . $holiday['starttime'] . '</td><td>' .
                        $holiday['endtime'] . '</td><td>'.$_leaveFor.'</td><td><a  onClick="onDelete('.$holiday['id'].',\''. $holiday['eventOn'].'\')">Delete</a></td></tr>';
            }
            $holidays_string.= '</table>';
        } else {
            $holidays_string.= 'unable to load Holidays';
        }

        $dataProvider = new CActiveDataProvider('ResourceTiming', array(
            'criteria' => array(
                'condition' => 'eventtype=\'' . ResourceTiming::TYPE_HOLIDAY . '\'',
                'order' => 'starttime DESC',
        )));
        $this->render('holiday', array(
            'dataProvider' => $dataProvider, 'resources' => User::getUsersByRole('employee'), 'daylist' => $holidays_string
        ));
    }
    
    public function actionGetHolidaysByDate(){
        $holidays_string = "";
        if (!isset($_REQUEST['date'])) {
            $date = date("Y-m-d");
        } else {
          //  $date = strtotime($_REQUEST['date']);
        }
//        if($date instanceof DateTime){
//            $date=$date->format("Y-m-d");
//        }
        $holidays=  ResourceTiming::getAllHolidays($_REQUEST['date']);
        if (isset($holidays)&&  sizeof($holidays)>0) {
            $holidays_string.= '<table  class="cmn_table"><tr><th>Date</th><th>Note</th><th>All day</th><th>Start</th><th>End</th><th>Holiday For</th><th></th></tr>';
            
            foreach ($holidays as $key => $holiday) {
                $_isAllDay='No';
                if(isset($holiday['allDay'])&&$holiday['allDay']==TRUE){
                    $_isAllDay='Yes';
                }
                $_leaveFor='Organization';
                if(isset($holiday['resource'])){
                    $_leaveFor=  User::model()->findByPk($holiday['resource'])->profile->name;
                }
                
                $holidays_string.='<tr><td>' . $holiday['eventOn'] . '</td><td>' . $holiday['note'] . '</td><td>' .
                $_isAllDay . '</td><td>' . $holiday['starttime'] . '</td><td>' .
                        $holiday['endtime'] . '</td><td>'.$_leaveFor.'</td><td><a  onClick="onDelete('.$holiday['id'].',\''. $holiday['eventOn'].'\')">Delete</a></td></tr>';
            }
            $holidays_string.= '</table>';
        } else {
            $holidays_string.= 'unable to load Holidays';
        }
        echo $holidays_string;
    }

    public function actionCreateHoliday() {
        if (!isset($_REQUEST['date'])) {
            $dataProvider = new CActiveDataProvider('ResourceTiming', array(
                'criteria' => array(
                    'condition' => 'eventtype=\'' . ResourceTiming::TYPE_HOLIDAY . '\'',
                    'order' => 'starttime DESC',
            )));
            $this->render('holiday', array(
                'dataProvider' => $dataProvider, 'resources' => User::getUsersByRole('employee')
            ));
        }
        try {
            $event = new ResourceTiming();
            $date = date('Y-m-d', strtotime($_REQUEST['date']));
            if (isset($_REQUEST['allday']) && $_REQUEST['allday'] == 'on') {
                $start = date_create_from_format('Y-m-d H:i:s', $date. '00:01:01');
                $end = date_create_from_format('Y-m-d H:i:s', $date . '23:59:59');
                $event->allDay=TRUE;
            } else {

                $start = date_create_from_format('Y-m-d H:i', $date . $_REQUEST['start']);
                $end = date_create_from_format('Y-m-d H:i', $date . $_REQUEST['end']);
                 $event->allDay=FALSE;
            }
            if (!(isset($_REQUEST['allOrg']) && $_REQUEST['allOrg'] == 'on')) {
                if (isset($_REQUEST['employee']) && $_REQUEST['employee'] != 0) {
                    $event->resource = $_REQUEST['employee'];
                } else {
                    throw new Exception('Invalid request : selected employee is not valid');
                }
            }
            if ($start >= $end) {
                throw new Exception("Invalid Start and End time");
            }
            $event->note = $_REQUEST['note'];
            $event->eventOn = $date;
            $event->starttime = $this->miliSecToFormated($start);
            $event->endtime =$this->miliSecToFormated($end);
            $event->duration = 0;
            $event->eventtype = ResourceTiming::TYPE_HOLIDAY;
            $event->save();
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
            return;
        }
        echo 'Saved';
    }
    private function miliSecToFormated($date) {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Conf the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Conf::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Conf $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'conf-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
